import {useUserStoreHook} from "/@/store/modules/user"
import {RouteLocationNormalized, Router, RouteRecordRaw} from "vue-router";
import {MenuModel} from "/@/api/system/model/MenuModel";
const modules = import.meta.glob('../../views/**/**.vue')
import {useMenuStoreHook} from "/@/store/modules/menu";
import store from 'store'
import NProgress from "nprogress";

const menuStore = useMenuStoreHook()
const affixList: MenuModel[] = []
export const  noIntercept = ['/login','/404']
/**
 * 固定路由
 */
const fixedRouterList: RouteRecordRaw[] = [
    {
        path: '/404',
        name: '404',
        component: import('/@/layout/page/404.vue')
    },
    {
        path: '/:pathMatch(.*)',
        name: 'noPage',
        redirect: '/404'
    }
]


export function beforeEach(router: Router) {
    router.beforeEach(async (to, from) => {
        let userStore = useUserStoreHook();
        if (noIntercept.includes(to.fullPath)) {

        } else if (!from.name && !userStore.menuLoad) {
            await userStore.getUserInfo()
            addFixedRouter(router);
            setCurrentTab(router, to)
        }else {
            let token = store.get('token');
            if(!token){
                router.push({
                    name: "login"
                })
            }
        }
        return true
    })
    router.afterEach((to, from) => {
        //主要是为了实现切换路由，显示路由tab页功能
        if(to.name && to.meta.ancestor && to.meta.ancestor instanceof Array && to.meta.ancestor!.length > 0){
            setRouterTab(to.meta.ancestor[to.meta.ancestor.length - 1])
        }
        //服务响应时完成进度条
        NProgress.done()

    })
}



/**
 * 加载路由
 */

export function loadRouter(menuInfo:MenuModel[], name: string, router: Router, ancestorRouter: MenuModel[]) {
    menuInfo.forEach(res => {
        if (res.children) {
            loadRouter(res.children, name, router, [...ancestorRouter, res])
        } else {
            let routerItem = {
                path: "/" + res.requestPath,
                name: res.name,
                meta: {
                    title: res.title,
                    keepAlive: true,
                    ancestor: [...ancestorRouter, res]
                },
                component: modules['../../views/' + res.filePath + '.vue'],
            } as RouteRecordRaw
            if (res.affix === 1) {
                affixList.push(res)
            }
            router.addRoute(name, routerItem)
        }
    })

}

/**
 * 设置当前Tab和固定tab栏
 * @param router
 */
export function setCurrentTab(router: Router, to: RouteLocationNormalized) {
    /**
     * 设置固定Tab栏
     */
    if (affixList && affixList.length > 0) {
        affixList.forEach(res=>{
            menuStore.addTab({
                name: res.name,
                title: res.title,
                affix: res.affix,
                activate: true
            })
        })
    }
    const path = to.path
    const routers = router.getRoutes()
    const currentRouter = routers.find(res => res.path === path);
    if (!currentRouter) {
        return;
    }
    const ancestor = currentRouter.meta.ancestor as MenuModel[]
    if (ancestor && ancestor.length > 0) {
        const currentMenu = ancestor[ancestor.length - 1]
        menuStore.addTab({
            name: currentMenu.name,
            title: currentMenu.title,
            affix: currentMenu.affix,
            activate: true
        })
        router.push({
            name: currentMenu.name
        })
    }
}


function addFixedRouter(router: Router) {
    fixedRouterList.forEach(res=>{
        router.addRoute(res.name!, res)
    })

}

function setRouterTab(menu: MenuModel) {
    menuStore.addTab({
        title: menu.title,
        name: menu.name,
        activate: true,
        affix: menu.affix
    })
}